package com.sky.controller.common;

import com.sky.domain.R;
import com.sky.entity.SysFile;
import com.sky.service.ISysFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 文件请求处理
 *
 * @author tzl
 */
@RestController
@RequestMapping("/files")
public class SysFileController
{
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileService sysFileService;


    /**
     * 文件上传请求
     */
    @PostMapping("/upload")
    public R<SysFile> upload(MultipartFile file) {
        try {
            // 上传并返回访问地址
            return R.ok(sysFileService.uploadFile(file));
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 文件上传请求
     */
    @PostMapping("/uploads")
    public R<List<SysFile>> uploads(MultipartFile[] files) {
        try {
            ArrayList<SysFile> list = new ArrayList<>();
            for (MultipartFile file : files) {
                // 上传并返回访问地址
                SysFile sysFile = sysFileService.uploadFile(file);
                list.add(sysFile);
            }
            return R.ok(list);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }

    /**
     * 文件删除
     */
    @DeleteMapping("/delete")
    public void delete(String fileName) {
        try {
            sysFileService.deleteFile(fileName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 获取文件byte[]
     */
    @GetMapping("/getObjectByte")
    public R<byte[]> getObjectByte(String objectName) {
        try {
            return R.ok(sysFileService.getObjectByte(objectName));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 获取文件byte[]
     */
    @PostMapping("/getObjectByteMap")
    public R<Map<String, byte[]>> getObjectByteMap(@RequestBody Map<String, String> keyToPath) {
        try {
            return R.ok(sysFileService.getObjectByteMap(keyToPath));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

}

